//
//  DynamicDownLoadViewController.m
//  EnjoyArkUIXIOS
//
//  Created by Dordly on 2024/3/7.
//

#import "DynamicDownLoadViewController.h"
#import "MainTableViewCell.h"
#import "PublicAlertView.h"
#import "DynamicShowViewController.h"
//#import <SSZipArchive/SSZipArchive.h>
#import "../SSZipArchive/SSZipArchive.h"


#define doc_path(_fileOrFolder) [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:_fileOrFolder]
#define FILE_ADDRESS            @"files/arkui-x"
#define URL_ADDRESS             @"https://note.youdao.com/yws/public/resource/7bcafc7245d02429559bf4092aa2f9c4/xmlnote/WEBRESOURCE805d29bc1f1f1d54a37352496300f1d9/3"

static NSString *const CELL = @"DynamicDownLoadTableViewCell";

@interface DynamicDownLoadViewController () <UITableViewDelegate, UITableViewDataSource, NSURLSessionDelegate, SSZipArchiveDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) PublicAlertView *publicAlertView;

@property (nonatomic, assign) BOOL isDownLocalSuccess;

@property (nonatomic, assign) BOOL isDownUrlSuccess;

@property (nonatomic, strong) NSMutableData *fileData;

@property (nonatomic, copy) NSString *pregressStr;

@property (nonatomic, strong) NSURLSession *session;

@property (nonatomic, strong) NSURLSessionTask *task;

@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, assign) NSInteger clickCount;

@property (nonatomic, assign) BOOL isUnzipLocal;
@property (nonatomic, strong) NSString* pathName;

@end

@implementation DynamicDownLoadViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigationBarWithCenterTitle:self.titleName];
    [self.view addSubview:self.mainTableView];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerClass:[MainTableViewCell class] forCellReuseIdentifier:CELL];
    [self.view addSubview:self.publicAlertView];
//    [self deleteDocumentInfoWithPathStr:@""];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = NO;
    [self setNewOrientation:NO];
}

- (void)setIsPortrait:(BOOL)isPortrait {
    if (!self.mainTableView) {
        return;
    }
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    if ((isPortrait && height < width) || (!isPortrait && width < height)) {
        width = self.view.frame.size.height;
        height = self.view.frame.size.width;
    }
    if (self.mainTableView.frame.size.width == width) {
        return;
    }
    self.mainTableView.frame = self.view.frame;
    [self.mainTableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL forIndexPath:indexPath];
    if (!cell) {
        cell = [[MainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL];
    }
    cell.titleName = self.dataArray[indexPath.row];
    cell.publicWidth = self.view.frame.size.width;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        {
            self.clickCount += 1;
            [self start];

        }
            break;
        case 1:
        {
            [self deleteDocumentInfoWithPathStr:@""];
            self.publicAlertView.titleStr = @"清除成功";
            [self.publicAlertView showView];
            self.isDownUrlSuccess = NO;
            self.isDownLocalSuccess = NO;
        }
            break;
        case 2:
        {
            //            [self unZip];
                        [self pushNextPage];
 
        }
            break;
            
        default:
            break;
    }
}

- (void)unZip {
    if (self.isDownLocalSuccess) {
        [self pushNextPage];
        return;
    }
    // 解压缩
    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"arkui-x" ofType:@"zip"];
    NSString *resultLocal = doc_path(FILE_ADDRESS);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        /// SSZipArchive 为三方库，需要手动引入，或者cocoapod引入
        self.isUnzipLocal = YES;
        [SSZipArchive unzipFileAtPath:pathStr toDestination:resultLocal delegate:self];
//        [SSZipArchive unzipFileAtPath:pathStr toDestination:resultLocal
//                      progressHandler:nil
//                    completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (succeeded) { // 解压成功后，进入效果界面
//                    [self pushNextPage];
//                    self.isDownLocalSuccess = YES;
//                }
//            });
//        }];
    });
}
- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath {
    NSLog(@"1");
    if (self.isUnzipLocal) {
        dispatch_async(dispatch_get_main_queue(), ^{
    //        if (succeeded) { // 解压成功后，进入效果界面
                [self pushNextPage];
                self.isDownLocalSuccess = YES;
    //        }
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
//            if (succeeded) { // 解压成功后，进入效果界面
                [self deleteDocumentInfoWithPathStr:self.pathName];
//                [self pushNextPage];
//            }
            self.isDownUrlSuccess = YES;
        });
    }

    
                
}
- (void)zipArchiveWillUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo {
    NSLog(@"1");
}

- (void)zipArchiveWillUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo {
    NSLog(@"1");
}
- (void)zipArchiveDidUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo {
    NSLog(@"1");
}

//1.获取NSURLSession
- (NSURLSession *)session {
    if (!_session) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

//2.开始下载任务
- (void)start {
    if (self.isDownUrlSuccess) {
//        [self pushNextPage];
        return;
    }
    NSURL *url = [NSURL URLWithString:URL_ADDRESS];
    self.task = [self.session downloadTaskWithURL:url];
    [self.task resume];
}

#pragma mark -- NSURLSessionDownloadDelegate

/// 下载数据写入本地（可能会调用多次）
/// @param bytesWritten 本次写入数据大小
/// @param totalBytesWritten 已经写入数据大小
/// @param totalBytesExpectedToWrite 总共需要写入数据大小
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    //获取下载进度
    NSString *pregress = [NSString stringWithFormat:@"%.f", (double)totalBytesWritten / totalBytesExpectedToWrite * 100];
    if (pregress.doubleValue > 99) {
        self.pregressStr = @"云端请求下载";
    } else {
        self.pregressStr = [NSString stringWithFormat:@"下载进度：%@%%", pregress];
    }
    [self.dataArray replaceObjectAtIndex:0 withObject:self.pregressStr];
    [self.mainTableView reloadData];
}

/// 恢复下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}

/// 下载完成调用
/// @param location 写入本地临时路经（temp文件夹里面）
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //获取服务器的文件名
    NSString *fileName = downloadTask.response.suggestedFilename;
    //创建需要保存在本地的文件路径
    NSString *filePath = [caches stringByAppendingPathComponent:fileName];
    //将下载的文件剪切到上面的路径
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:filePath error:nil];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:filePath]) {
        return;
    }
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{ // 解压缩
        NSString *resultLocal = doc_path(FILE_ADDRESS);
        self.isUnzipLocal = NO;
        self.pathName = fileName;
        [SSZipArchive unzipFileAtPath:filePath toDestination:resultLocal delegate:self];
//        [SSZipArchive unzipFileAtPath:filePath toDestination:resultLocal
//                      progressHandler:nil
//                    completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (succeeded) { // 解压成功后，进入效果界面
//                    [self deleteDocumentInfoWithPathStr:fileName];
//                    [self pushNextPage];
//                }
//                self.isDownUrlSuccess = succeeded;
//            });
//        }];
    });
}


/// 删除缓存
- (void)deleteDocumentInfoWithPathStr:(NSString *)pathStr {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    if ([pathStr isEqualToString:@""]) {
        pathStr = FILE_ADDRESS;
    }
    for (NSString *path in files) {
        NSError *error = nil;
        if (![path containsString:pathStr]) {
            continue;
        }
        NSString *filePath = [cachePath stringByAppendingPathComponent:path];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        }
    }
    if (pathStr.length < 1) {
        self.clickCount = 0;
    }
    NSArray *files1 = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    NSLog(@"1");
}

- (void)pushNextPage {
//    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
//    NSMutableArray *moduleArray = [NSMutableArray array];
//    int NowCount = 3;
//    if (self.isUnzipLocal) {
//        NowCount = 4;
//    }
//    for (NSString *path in files) {
//        NSArray *pathArray = [path componentsSeparatedByString:@"/"];
//        /// 此部分为拿到需要动态化加载的module的名称信息
//        if (pathArray.count == NowCount && ([pathArray containsObject:@"fang_application"] || [pathArray containsObject:@"dynamicdemo"])) {
//            [moduleArray addObject:pathArray.lastObject];
//        }
//    }
    DynamicShowViewController *dynamicVC = [[DynamicShowViewController alloc] init];
//    if (self.clickCount >= moduleArray.count) {
//        self.clickCount = moduleArray.count;
//        self.clickCount -= 1;
//    }
//    if (self.clickCount < moduleArray.count) {
//        dynamicVC.moduleName = moduleArray[self.clickCount];
//    }
//    NSString *changeNameStr;
//    if(dynamicVC.moduleName && dynamicVC.moduleName.length > 0) {
//        changeNameStr = [dynamicVC.moduleName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[dynamicVC.moduleName substringToIndex:1] capitalizedString]];
//    }
//    dynamicVC.abilityName = [NSString stringWithFormat:@"%@Ability", changeNameStr];
    dynamicVC.hidesBottomBarWhenPushed = YES;
    dynamicVC.moduleName = @"fang_application";
    dynamicVC.abilityName = @"Fang_applicationAbility";
    [self.navigationController pushViewController:dynamicVC animated:YES];
}

- (PublicAlertView *)publicAlertView {
    if (!_publicAlertView) {
        _publicAlertView = [[PublicAlertView alloc] initWithFrame:self.view.frame mainTitle:@""];
    }
    return _publicAlertView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] initWithArray:@[@"云端请求下载", @"删除沙箱下的动态化资源", @"打开动态化页面"]];
    }
    return _dataArray;
}

@end
